package com.autobet.utils;

import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

/**
 * Created by yangd on 2017-08-27.
 */
public class HttpUtils {

    private static final Logger log = LoggerFactory.getLogger(HttpUtils.class);

    public HttpUtils() {
    }

    public static String post(String postUrl, Map<String, String> headerMap) {
        return post(postUrl, (Map)null, headerMap);
    }

    public static String post(String postUrl) {
        return post(postUrl, (Map)null, (Map)null);
    }

    public static String post(String postUrl, Map<String, String> paraMap, Map<String, String> headerMap) {
        String responseResult = "";
        //采用绕过验证的方式处理https请求
        SSLContext sslcontext = null;
        try {
            sslcontext = createIgnoreVerifySSL();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        }

        // 设置协议http和https对应的处理socket链接工厂的对象
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.INSTANCE)
                .register("https", new SSLConnectionSocketFactory(sslcontext))
                .build();
        PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        HttpClients.custom().setConnectionManager(connManager);

        //创建自定义的httpclient对象
        CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(connManager).build();
//        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httppost = new HttpPost(postUrl);
        List<NameValuePair> formparams = null;
        boolean paraflag = false;
        String key;
        if(paraMap != null && !paraMap.isEmpty()) {
            paraflag = true;
            formparams = new ArrayList();
            Iterator it = paraMap.keySet().iterator();

            while(it.hasNext()) {
                key = (String)it.next();
                key = (String)paraMap.get(key);
                formparams.add(new BasicNameValuePair(key, key));
            }
        }

        try {
            if(paraflag) {
                UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
                httppost.setEntity(uefEntity);
            }

            if(headerMap != null && !headerMap.isEmpty()) {
                Iterator it = headerMap.keySet().iterator();

                while(it.hasNext()) {
                    key = (String)it.next();
                    String value = (String)headerMap.get(key);
                    httppost.setHeader(key, value);
                }
            }

//            httppost.setHeader("Content-type", "application/x-www-form-urlencoded");
            httppost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36");

            log.info("请求地址：" + postUrl);
            CloseableHttpResponse response = httpclient.execute(httppost);

            try {
                HttpEntity entity = response.getEntity();
                if(entity != null) {
                    responseResult = EntityUtils.toString(entity, "UTF-8");
                }
            } catch (Exception var28) {
                log.error("http请求错误", var28);
            } finally {
                response.close();
            }
        } catch (Exception var30) {
            log.error("http请求错误", var30);
        } finally {
            try {
                httpclient.close();
            } catch (Exception var27) {
                log.error("http请求错误", var27);
            }

        }

        return responseResult;
    }

    public static String postPayload(String postUrl, String payload, Map<String, String> headerMap) {
        String responseResult = "";
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httppost = new HttpPost(postUrl);

        try {
            StringEntity se = new StringEntity(payload, "utf-8");
            httppost.setEntity(se);
            if(headerMap != null && !headerMap.isEmpty()) {
                Iterator it = headerMap.keySet().iterator();

                while(it.hasNext()) {
                    String key = (String)it.next();
                    String value = (String)headerMap.get(key);
                    httppost.setHeader(key, value);
                }
            }

            log.info("请求地址：" + postUrl);
            CloseableHttpResponse response = httpclient.execute(httppost);

            try {
                log.info("响应吗：{}", Integer.valueOf(response.getStatusLine().getStatusCode()));
                if(response.getStatusLine().getStatusCode() != 200) {
                    throw new Exception("请求没有返回200响应码");
                }

                HttpEntity entity = response.getEntity();
                if(entity != null) {
                    responseResult = EntityUtils.toString(entity, "UTF-8");
                }
            } catch (Exception var26) {
                log.error("http请求错误", var26);
            } finally {
                response.close();
            }
        } catch (Exception var28) {
            log.error("http请求错误", var28);
        } finally {
            try {
                httpclient.close();
            } catch (Exception var25) {
                log.error("http请求错误", var25);
            }

        }

        return responseResult;
    }

    /**
     * 绕过验证
     *
     * @return
     * @throws NoSuchAlgorithmException
     * @throws KeyManagementException
     */
    public static SSLContext createIgnoreVerifySSL() throws NoSuchAlgorithmException, KeyManagementException {
        SSLContext sc = SSLContext.getInstance("SSLv3");

        // 实现一个X509TrustManager接口，用于绕过验证，不用修改里面的方法
        X509TrustManager trustManager = new X509TrustManager() {
            @Override
            public void checkClientTrusted(
                    java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
                    String paramString) throws CertificateException {
            }

            @Override
            public void checkServerTrusted(
                    java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
                    String paramString) throws CertificateException {
            }

            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };

        sc.init(null, new TrustManager[] { trustManager }, null);
        return sc;
    }


    /**
     * 模拟请求
     *
     * @param url        资源地址
     * @param map    参数列表
     * @param encoding    编码
     * @return
     * @throws NoSuchAlgorithmException
     * @throws KeyManagementException
     * @throws IOException
     * @throws ClientProtocolException
     */
    public static String send(String url, Map<String,String> map,String encoding) throws KeyManagementException, NoSuchAlgorithmException, ClientProtocolException, IOException {
        String body = "";
        //采用绕过验证的方式处理https请求
        SSLContext sslcontext = createIgnoreVerifySSL();

        // 设置协议http和https对应的处理socket链接工厂的对象
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.INSTANCE)
                .register("https", new SSLConnectionSocketFactory(sslcontext))
                .build();
        PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        HttpClients.custom().setConnectionManager(connManager);

        //创建自定义的httpclient对象
        CloseableHttpClient client = HttpClients.custom().setConnectionManager(connManager).build();
//        CloseableHttpClient client = HttpClients.createDefault();

        //创建post方式请求对象
        HttpPost httpPost = new HttpPost(url);

        //装填参数
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        if(map!=null){
            for (Map.Entry<String, String> entry : map.entrySet()) {
                nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
        }
        //设置参数到请求对象中
        httpPost.setEntity(new UrlEncodedFormEntity(nvps, encoding));

        System.out.println("请求地址："+url);
        System.out.println("请求参数："+nvps.toString());

        //设置header信息
        //指定报文头【Content-type】、【User-Agent】
        httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
        httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

        //执行请求操作，并拿到结果（同步阻塞）
        CloseableHttpResponse response = client.execute(httpPost);
        //获取结果实体
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            //按指定编码转换结果实体为String类型
            body = EntityUtils.toString(entity, encoding);
        }
        EntityUtils.consume(entity);
        //释放链接
        response.close();
        return body;
    }

}
